package com.cmz.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * HTTP 工具
 * @author cmz
 */
@Slf4j
public class HttpUtils {

    public static void trustAllHttpsCertificates() {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new IgnoreTrustManager();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = null;
        try {
            sc = javax.net.ssl.SSLContext.getInstance("SSL","SunJSSE");
            sc.init(null, trustAllCerts, null);
        } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyManagementException e) {
            log.error("Failed handling SSL Certification: ", e);
        }
        if (sc!=null) {
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }
    }

    private static class IgnoreTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            // do nothing
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            // do nothing
        }
    }

}
